import { execSync } from "child_process";
import {v4} from 'uuid'
import * as CONSTANT from './constants';
import fs from 'fs';
export default new class {
    safeJsonParse(object) {
        try {
            return JSON.parse(object);
        } catch (error) {
            return error.toString();
        }
    }

    command(cmd) {
        let response = execSync(cmd) || '';

        return response.toString();
    }

    //去除空格
    trim(str) {

        return str.replace(/(^\s*)|(\s*$)/g, "");

    }

    //判断obj是否在arr里面
    contains(arr, obj, key) {
        var i = arr.length;
        while (i--) {
            let cur = arr[i];
            if (key) {
                if (cur[key] == obj[key] || cur[key] == obj[key].toString().toUpperCase()) {
                    return true;
                }
            } else {
                if (cur === obj || cur === obj.toString().toUpperCase()) {
                    return true;
                }
            }

        }

        return false;
    }

    js2Json(data) {
        let mod = "module.exports = " + data + CONSTANT.EOL;

        let fileName = process.cwd() + "/" + v4() + ".js";
        fs.writeFileSync(fileName, mod);
        let res = require(fileName);
        return res;
    }

    //去除一行文件中多余的空格
    trimSpace(line) {
        //解析空格和tab
        let data = line.split(' ');
        if(data.length == 0) {
            data = line.split('\t');
        }
        for(let i=0;i<data.length;i++) {
            if(this.trim(data[i]) == "") {
                data.splice(i,1);
                i--;
            }
        }
        return data;
    }




}()